package com.aierkeji.call.cms.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.aierkeji.call.cms.contants.Contants;
import com.aierkeji.call.cms.entity.AkjCallUser;
import com.aierkeji.call.cms.util.AppConfig;
import com.aierkeji.call.cms.util.GsonUtils;
import com.aierkeji.call.cms.util.HttpUtils;
import com.aierkeji.call.cms.util.ResultMapHelper;
import com.aierkeji.call.cms.util.StringUtils;

@Service
public class AkjCallB2cService {
	private final Logger log = LogManager.getLogger(AkjCallB2cService.class);

	@Value("${b2c.base.url:DefaultValue}")
	private String baseUrl;


	@Value("${b2c.getYZM.url:DefaultValuel}")
	private String getYZM;

	@Value("${b2c.logingByYzm.url:DefaultValuel}")
	private String logingByYzm;
	
	@Value("${b2c.updateStatistics.url:DefaultValuel}")
	private String updateStatistics;
	
	
	@Value("${cmsApiToken:DefaultValue}")
	private String cmsApiToken;

	private Map<String, String> getHeadMap() {
		Map<String, String> map = new HashMap<>();
		map.put("cmsApiToken", cmsApiToken);
		return map;
	}

	public Boolean checkResult(String resp) {

		Map<String, Object> map = changeResult(resp);
		return ResultMapHelper.isSuccess(map);
	}

	public Map<String, Object> changeResult(String resp) {
		if (StringUtils.isEmpty(resp)) {
			return null;
		}
		try {
			Map<String, Object> map = GsonUtils.fromJson(resp, Map.class);
			return map;
		} catch (Exception e) {
			// TODO: handle exception
			log.error("", e);
		}
		return null;
	}

	private String send(String url, Map<String, Object> map) {
		if ("dev".equals(AppConfig.getProperty("envType"))) {
			log.info("in dev return success");
			return GsonUtils.parseToJson(ResultMapHelper.success());
		} else {
			String resp = HttpUtils.postMethodWithJsonHeader(url, map, getHeadMap());
			return resp;
		}
	}


	public Map<String, Object> getYzm(Map<String, Object> map) {
		// TODO Auto-generated method stub
		String resp = this.send(baseUrl + getYZM, map);
		return changeResult(resp);
	}

	public Map<String, Object> logingByYzm(Map<String, Object> map) {
		String resp = this.send(baseUrl + logingByYzm, map);
		return changeResult(resp);
	}
	
	public Map<String, Object> updateStatistics(Map<String, Object> map) {
		AkjCallUser akjCallUser = (AkjCallUser) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
		String idString = String.valueOf(akjCallUser.getId());
		if(akjCallUser.checkRole(Contants.ROLE_ID_STATISTICIAN)) {
			idString = String.valueOf(akjCallUser.getLeaderId());
		}
		map.put("leaderId", idString);
		
		String resp = this.send(baseUrl + updateStatistics, map);
		return changeResult(resp);
	}
}
